package com.df.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;

public class TimeUtil {


    public static String[] getLast12Months() {
        String[] months = new String[12];
        LocalDate today = LocalDate.now();
        for (int i = 12; i > 0; i--) {
            LocalDate localDate = today.minusMonths(i);
            months[12 - i] = localDate.toString();
        }
        return months;
    }



    /**
     * 获取某个月的最后一天
     * @param dateStr  yyyy-MM-dd
     * @return
     */
    public static String getMonthEnd(String dateStr) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(dateStr);
            Calendar c = Calendar.getInstance();
            c.setTime(date);

            //设置为当月最后一天
            c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
            //将小时至23
            c.set(Calendar.HOUR_OF_DAY, 23);
            //将分钟至59
            c.set(Calendar.MINUTE, 59);
            //将秒至59
            c.set(Calendar.SECOND,59);
            //将毫秒至999
            c.set(Calendar.MILLISECOND, 999);
            // 获取本月最后一天的时间戳

            return sdf.format(new Date(c.getTimeInMillis()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date());
        String[] months = TimeUtil.getLast12Months();
        for (String month : months) {
            System.out.println(TimeUtil.getMonthEnd(month));
        }
    }
}
